﻿using NetDh.Lib;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace NetDh.Presentation.Common
{
    [MvcActionFilter]
    public class BaseMvcController : Controller
    {
        /// <summary>
        /// 获取当前请求的UserToken
        /// </summary>
        public UserToken CurrentUser
        {
            get
            {
                var token = this.HttpContext.Items[TokenHelper.TOKEN_NAME] as UserToken;
                if (token.UserId == null) return null;
                return token;
            }
        }
        /// <summary>
        /// 返回值支持Newtonsoft.Json的序列化，支持参数obj的属性别名[JsonProperty]。
        /// </summary>
        /// <returns></returns>
        public ActionResult NewJson(object obj)
        {
            var str = JsonConvert.SerializeObject(obj);
            return Content(str, "application/json");
        }

        protected override void OnException(ExceptionContext filterContext)
        {
            //-->这里捕获的异常，没有包含404等非内部代码异常。
            ////示例代码
            //filterContext.Result = new ContentResult() { Content = "catch exception" };//在OnActionExecuted输出。然后不会再输出OnResultExecuting
            //filterContext.ExceptionHandled = true;//如果为true，则异常会吃掉，不会往下抛，不会到Global.asax.cs的Application_Error中。
            base.OnException(filterContext);
        }
        protected override void OnAuthorization(AuthorizationContext context)
        {
            ////源码中判断是否有[AllowAnonymous]标记的代码
            //bool flag = context.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) || context.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);
            //if (flag) return;
            //context.HttpContext.Response.Write("BaseController OnAuthorization. <br/> ");
            base.OnAuthorization(context);
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //先于各FilterAttribute时机点
            base.OnActionExecuting(filterContext);
        }
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
        }
        protected override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            base.OnResultExecuting(filterContext);
        }
        protected override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            base.OnResultExecuted(filterContext);
        }
    }
}
